package logic

import (
	"context"
	"shop/model/mysql"
	"shop/model/redis"

	"shop/goods"
	"shop/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartCreateLogic {
	return &CartCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartCreateLogic) CartCreate(in *goods.CartCreateRequest) (*goods.CartCreateResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.FindInfoGoodsName(in.GoodsTitle)
	if err != nil {
		logx.Error("获取商品失败:", err)
		return nil, err
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, err
	}
	stocke := redis.SynGoodsIdStock(in.GoodsNum, int64(g.ID))
	if stocke < in.GoodsNum {
		logx.Error("当前库存不足")
		return nil, err
	}
	CartMap := []*mysql.Goods{}
	if redis.CartEx(in.UserId, int64(g.ID)) {
		err = redis.CartUp(in.UserId, int64(g.ID), in.GoodsNum)
		if err != nil {
			logx.Error("更新数据失败")
			return nil, err
		}
	} else {
		err = redis.CartCreate(in.UserId, int64(g.ID), CartMap)
		if err != nil {
			logx.Error("购物车添加失败")
			return nil, err
		}
	}
	return &goods.CartCreateResponse{
		Success: true,
	}, nil
}
